package de.jmda.home.ui.vaadin.usermgmt;

import com.google.common.eventbus.Subscribe;
import com.vaadin.ui.Component;
import com.vaadin.ui.ComponentContainer;
import com.vaadin.ui.Notification;

import de.jmda.common.ui.web.vaadin.service.DefaultSessionContext;

public class UserComponentController
{
	private Component containerContent;
	
	private ComponentContainer container;

	public UserComponentController(ComponentContainer container)
	{
		super();

		this.container = container;
		
		init();
	}

	private void init()
  {
		String username = DefaultSessionContext.get().getUsername();

		if (username == null)
		{
			containerContent = new UserLoginRegisterComponent();
		}
		else
		{
			containerContent = new UserDisplayComponent(username);
		}
		
		container.addComponent(containerContent);

		DefaultSessionContext.get().getEventBus().register(this);
  }

	@Subscribe
	public void handle(EventLoginStart event)
	{
		Component newContainerContent = new UserLoginComponent(new AuthenticatorDB());
		container.replaceComponent(containerContent, newContainerContent);
		containerContent = newContainerContent;
	}

	@Subscribe
	public void handle(EventRegisterStart event)
	{
		Component newContainerContent = new UserRegistrationComponent();
		container.replaceComponent(containerContent, newContainerContent);
		containerContent = newContainerContent;
	}

	@Subscribe
	public void handle(EventLogin event)
	{
		String username = DefaultSessionContext.get().getUsername();

		if (username != null)
		{
			Component newContainerContent = new UserDisplayComponent(username);
			container.replaceComponent(containerContent, newContainerContent);
			containerContent = newContainerContent;
		}
	}

	@Subscribe
	public void handle(EventLoginCancel event)
	{
		Component newContainerContent = new UserLoginRegisterComponent();
		container.replaceComponent(containerContent, newContainerContent);
		containerContent = newContainerContent;
	}

	@Subscribe
	public void handle(EventLogout event)
	{
		Component newContainerContent = new UserLoginRegisterComponent();
		container.replaceComponent(containerContent, newContainerContent);
		containerContent = newContainerContent;
	}

	@Subscribe
	public void handle(EventChangePassword event)
	{
		Component newContainerContent = new UserChangePasswordComponent();
		container.replaceComponent(containerContent, newContainerContent);
		containerContent = newContainerContent;
	}

	@Subscribe
	public void handle(EventChangePasswordCancel event)
	{
		Component newContainerContent = new UserDisplayComponent();
		container.replaceComponent(containerContent, newContainerContent);
		containerContent = newContainerContent;
	}
}